#include "VFile.h"
#include "VTranslate.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QFileInfo>
#include <QTextCodec>
#include <QString>
#include <QDir>

VFile::VFile()
{

}

QString VFile::read_file_text_gbk(QString path, bool translate)
{
    QString result;
    QFile file(path);
    if(file.open(QFile::ReadOnly) == false)
    {
        qDebug() <<   "QString read_file_text(QString path) : open file error!";
        return result;
    }

    QTextStream in(&file);
    in.setCodec("gbk");
    result = GBK2UTF8(in.readAll());
    file.close();

    QString suffix = QFileInfo(path).suffix();
    if(translate && (suffix == "h" || suffix == "c"))
    {
        VTranslate trans;
        trans.en_cn_map_clear();
        trans.en_cn_map_append_keyword();
        trans.set_comment_skip(true);
        trans.set_qutation_skip(true);
        result = trans.get_cn_text(result);
    }

    return result;
}

void VFile::save_file_text_gbk(QString path, QString text, bool translate)
{
    QFile file(path);
    if (!file.open(QFile::WriteOnly))
    {
        qDebug() << "open error";
    }

    QString suffix = QFileInfo(path).suffix();
    if(translate && (suffix == "h" || suffix == "c"))
    {
        VTranslate trans;
        trans.cn_en_map_append_keyword();
        trans.set_comment_skip(true);
        trans.set_qutation_skip(true);

        text = trans.get_en_text(text);
    }

    QTextStream out(&file);
    out.seek(0);
    out.setCodec("gbk");
    out << UTF82GBK(text);
    out.seek(0);
    file.close();
}

void VFile::clear_folder_file(QString path, QString suffixs)
{
    QDir dir(path);
    foreach(QFileInfo mfi ,dir.entryInfoList())
    {
        if(mfi.isFile() && suffixs.indexOf("("+mfi.suffix()+")") != -1)
        {
            QFile(mfi.filePath()).remove();
        }
    }
}

QString VFile::GBK2UTF8(const QString &inStr)
{
    QTextCodec *gbk = QTextCodec::codecForName("GB18030");
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");

    QString g2u = gbk->toUnicode(gbk->fromUnicode(inStr));              // gbk  convert utf8
    return g2u;
}

QString VFile::UTF82GBK(const QString &inStr)
{
    QTextCodec *gbk = QTextCodec::codecForName("GB18030");
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");

    QString utf2gbk = gbk->toUnicode(inStr.toLocal8Bit());
    return utf2gbk;
}
